<template>
  <el-table :data="skuList" style="width: 100%">
    <el-table-column label="属性组合">
      <el-table-column v-for="(item, index) in skuList[0].saleAttributeList" :key="index"
                       :label="item.attrName">
        <template #default="scope">
          <span>{{ scope.row.saleAttributeList[index].attrValue }}</span>
        </template>
      </el-table-column>
    </el-table-column>
    <el-table-column prop="skuName" label="商品名称" width="180">
      <template #default="scope">
        <el-input v-model="scope.row.skuName"></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="skuTitle" label="标题">
      <template #default="scope">
        <el-input v-model="scope.row.skuTitle"></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="price" label="价格">
      <template #default="scope">
        <el-input v-model="scope.row.price" type="number"></el-input>
      </template>
    </el-table-column>
    <el-table-column prop="price" label="库存">
      <template #default="scope">
        <el-input v-model="scope.row.stock" type="number"></el-input>
      </template>
    </el-table-column>
    <el-table-column type="expand">
      <template #default="scope">
        <div>
          <el-upload
              v-model:file-list="scope.row.fileShowList"
              action="/api/file/upload/serve/re-market"
              list-type="picture-card"
              :on-success="(response, file, fileList) => handleUpload(response, file, fileList, scope.row)"
              :on-remove="(file, fileList) => handleRemove(file, fileList, scope.row)"
          >
            <el-icon>
              <Plus/>
            </el-icon>
            <template #file="{ file }">
              <div
                  :class="{'el-upload-list__item-thumbnail-container': true, 'default-pic': file.url === scope.row.defaultPic}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><zoom-in/></el-icon>
                  </span>
                  <span class="el-upload-list__item-delete"
                        @click="handleRemove(file, scope.row.fileShowList, scope.row)">
                    <el-icon><Delete/></el-icon>
                  </span>
                  <span class="el-upload-list__item-set-default" @click="setDefaultPic(file, scope.row)">
                    <el-icon><Star/></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image"/>
          </el-dialog>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <el-row :gutter="20" justify="center">
    <el-col :span="3">
      <div>
        <el-button type="primary" @click="last">上一步</el-button>
      </div>
    </el-col>
    <el-col :span="3" :offset="4">
      <div>
        <el-button type="success" @click="save">提交</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import {onMounted, onUnmounted, ref} from 'vue'
import {useGoodsFormStore} from "@/stores/form/goods-form";
import {Picture} from '@element-plus/icons-vue'
import type {AttributeAndValuesDTO, SkuAttribute, Sku} from "@/api/serve/re-market/type";

const formStore = useGoodsFormStore()
let dialogVisible = ref(false)
let dialogImageUrl = ref('')
let skuList = ref([])//skuList:[{saleAttributeList:[],skuName:'',skuTitle:'',spuId:null,categoryId:null,defaultPic:'',price:0,skuDescription:'',stock:0}]

onMounted(() => {
  //初始化skuList，防止修改销售属性，每次到达当前页面都重新计算
  backtracking(formStore.addGoodsForm.saleAttributeList, [], 0)
})

//利用回溯算法，进行对销售属性进行遍历，然后组合销售属性生成sku
let backtracking = (attrs: AttributeAndValuesDTO[], collect, attrIndex: number) => {
  // 终止条件：已经遍历完所有属性
  if (attrIndex >= attrs.length) {
    //构造sku
    let skuItem = {
      saleAttributeList: [...collect], // 使用副本避免引用问题
      skuName: '',
      skuTitle: '',
      spuId: null,
      categoryId: formStore.addGoodsForm.spuInfo.categoryId,
      defaultPic: '',
      price: 0,
      skuDescription: '',
      stock: 0,
      skuPictureList: [],
      fileShowList: []//仅用作回显
    }
    skuList.value.push(skuItem)
    return;
  }
  const currentAttr = attrs[attrIndex];
  // 遍历当前属性的所有值
  for (let i = 0; i < currentAttr.attributeValues.length; i++) {
    let attribute = {
      attributeId: currentAttr.attributeId,
      attrName: currentAttr.attrName,
      searchType: currentAttr.searchType,
      valueSelect: currentAttr.valueSelect,
      attrType: currentAttr.attrType,
      status: currentAttr.status,
      categoryId: currentAttr.categoryId,
      quickShow: currentAttr.quickShow,
      attrValue: currentAttr.attributeValues[i]
    }
    // 将当前销售属性添加到收集的属性集合中
    collect.push(attribute)

    // 递归调用，处理下一个属性，从第一个值开始
    backtracking(attrs, collect, attrIndex + 1)
    // 回溯：将当前销售属性从收集的属性集合中移除
    collect.pop()
  }
}

let handleUpload = (res, file, fileList, sku) => {
  // 假设后端返回的文件路径在 res.data 中
  const filePath = res.data;
  // 找到对应的文件对象并更新其 url
  const fileIndex = fileList.findIndex(f => f.uid === file.uid);
  if (fileIndex !== -1) {
    fileList[fileIndex].url = filePath;
  }
  // 将文件路径添加到 skuPictureList
  sku.skuPictureList.push(filePath);
}
let handleRemove = (file, fileList, sku) => {
  // 从 fileList 中移除文件对象
  sku.fileShowList = fileList;
  // 从 skuPictureList 中移除文件路径
  sku.skuPictureList = sku.skuPictureList.filter(path => path !== file.url);
}
let handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

let setDefaultPic = (file, sku) => {
  sku.defaultPic = file.url;
}

function last() {
  formStore.back()
}

function save() {
  formStore.submitForm()
}

onUnmounted(() => {
  if (formStore.addGoodsForm.skuList.length === 0) {
    formStore.setSkuList(skuList.value)
  }
})
</script>


<style scoped>.el-upload-list__item-thumbnail-container {
  position: relative;
  display: inline-block;
}

.el-upload-list__item-thumbnail-container.default-pic .el-upload-list__item-thumbnail {
  border: 4px solid #409EFF; /* 蓝色边框 */
  box-sizing: border-box;
}

.el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.el-upload-list__item-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
}

.el-upload-list__item-thumbnail-container:hover .el-upload-list__item-actions {
  opacity: 1;
}

.el-upload-list__item-actions span {
  display: inline-block;
  cursor: pointer;
  margin: 0 8px;
}
</style>
